package info.marlan.sipgate;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
/**
 * 
 * @author mark@marlan.info
 *
 */

public class CrashReportActivity extends Activity{
	
	public final static String CRASHREPORT = "stack.trace";
	private String trace = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		sendException(this);
	}
	
	
	public void sendException(Context context){
		String line = null;
		
		try {

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					context.openFileInput(CrashReportActivity.CRASHREPORT)));
			while ((line = reader.readLine()) != null) {
				trace += line + "\n";
			}
		} catch (FileNotFoundException fnfe) {
			// ...
		} catch (IOException ioe) {
			// ...
		}

        final AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(R.string.crashreporttitle);
        builder.setCancelable(true);
        builder.setPositiveButton(R.string.crashreportaccept, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            	Runnable runner = new Runnable() {
					public void run() {
							executeHttpPost(trace);
					}
				
				};
				new Thread(runner).start();
            	
            	CrashReportActivity.this.finish();
            }
        });
        builder.setNegativeButton(R.string.crashreportrefuse, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            	CrashReportActivity.this.finish();
            }
        });
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            public void onCancel(DialogInterface dialog) {
            	CrashReportActivity.this.finish();
            }
        });
      
        builder.setMessage(getString(R.string.crashreportmessage) + "\n\n" + trace);
        builder.create().show();

		context.deleteFile(CrashReportActivity.CRASHREPORT);
	}
    
	public static boolean fileExists(String file, Context context){
    	String[] files = context.fileList();
    	System.out.println(files);
    	if(files==null || file == null){
    		return false;
    	}
    	for(int i=0;i<files.length;i++){
    		if(file.equals(files[i])){
    			return true;
    		}
    	}
    	return false;
    }
	

	public String executeHttpPost(String error)  {
		BufferedReader in = null;
		String result = null;
		try {
			HttpClient client = new DefaultHttpClient();
			HttpPost request = new HttpPost(
					"http://track.webhop.net/track.php");
			List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
			postParameters.add(new BasicNameValuePair("error",error));
			UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
					postParameters);
			request.setEntity(formEntity);
			HttpResponse response = client.execute(request);
			in = new BufferedReader(new InputStreamReader(response.getEntity()
					.getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			result = sb.toString();
			
		}catch (Exception e) {
			// noop
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}
}
